package com.pet.shop.intercepters;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
import com.pet.config.SessionConstants;
import com.pet.shop.entity.user.UserInfo;
import com.pet.shop.utils.ApiResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by nmcmd on 16/1/22.
 */
public class AppSecurityInterceptor implements HandlerInterceptor {

    private static ObjectMapper mapper = null;
    private static final Logger logger = LoggerFactory.getLogger(AppSecurityInterceptor.class);

    private static ObjectMapper getMapper() {
        if (mapper == null) {
            mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
            mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
        }
        return mapper;
    }

    protected Map<String, Object> transToMAP(Map<String, String[]> parameterMap) {
        // 返回值Map
        Map<String, Object> returnMap = new HashMap<>();
        Iterator entries = parameterMap.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = request.getRequestedSessionId();
        Map<String, Object> returnMap = new HashMap<>();
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(SessionConstants.APP_SESSION_KEY);;
        if(userInfo == null && sessionId != null){
            userInfo = SessionConstants.sessionUserMap.remove(sessionId);
            if(userInfo != null) request.getSession().setAttribute(SessionConstants.APP_SESSION_KEY, userInfo);
        }
        if(userInfo == null){
            logger.error("当前的访问的 sessionId = {} 未授权，要先授权", sessionId);
            returnMap.put("code", HttpStatus.FORBIDDEN.value());
            returnMap.put("msg", "请先授权登录获取 openid ");
            write(response, returnMap);
            return false;
        }else{
            logger.info("当前的访问的 sessionId = {}, userInfo = {}", sessionId, JSONObject.toJSONString(userInfo));
        }
        return true;
    }

    private void write(HttpServletResponse response, Map<String, Object> map) {
        try {
            response.setContentType("application/json; charset=UTF-8");
            String json = getMapper().writeValueAsString(map);
            response.getWriter().print(json);
        } catch (Exception ex) {
            // ignore
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
